// pages/bindMail/bindMail.js
const noticeFile = require("../../utils/notice.js");
const Toast = noticeFile.Toast;
const requestFile = require("../../utils/request.js");
const request = requestFile.request;
const routerFile = require("../../utils/router.js");
const router = routerFile.router;
Page({
  data: {
    hidden: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  mailInput: function(e) {
    const mailPattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    const value = e.detail.value;
    if (mailPattern.test(value)) {
      // 校验通过
      this.setData({
        hidden: true,
      })
    } else {
      this.setData({
        hidden: false,
      })
    }
  },
  
  bindMail: function(e) {
    var that = this;
    const userModal = wx.getStorageSync('user');
    if (userModal == undefined || userModal == null || userModal == "") {
      wx.navigateTo({
        url: 'pages/login/login',
      })
      return;
    }
    const mail = e.detail.value.mail;
    if (mail == undefined || mail == null || mail == "") {
      Toast.fail("邮箱不能为空！");
      return;
    } else {
      const mailPattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      if (!mailPattern.test(mail)) {
        Toast.fail("邮箱格式不正确！");
      } else {
        request(router.bindMail, "POST", {
          userModal: userModal,
          mail: mail,
        }).then (function(res) {
          const code = res.data.code;
          if (code == 200) {
            const eventChannel = that.getOpenerEventChannel();
            eventChannel.emit("onMailBinded", {})
            wx.navigateBack({
              delta: 1,
            })
          } else {
            Toast.fail("服务器错误");
          }
        })
      }
    }
  }
})